import { defineStore } from 'pinia'
import request from '@/axios/utils/request'
import stringUtil from '@/utils/stringUtil'
import websocket from '@/utils/websocket'
import { useGlobalStore } from '@/stores/globalStore'

export const useChatStore = defineStore('chat', {
  state: () => ({
    hasLogin: !!localStorage.getItem('hasLogin'),
    sessionKey: localStorage.getItem('sessionKey') || '',
    messegeNum: [],
    systemConfig: JSON.parse(localStorage.getItem('system_config')) || {
      vibrate: true,
      bell: true,
    },
    onlineArray: [],
    isSocketOpen: false,
    token: localStorage.getItem('token') || '',
    loginUserInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    personMessage: [], // [{ sessionId, list: [msg, ...] }]
    lastUpdateSession: { id: '', count: 0 },
    editingGroupInfo: null,
    friendList: [],
    friendListShow: [],
    sessionList: [],
    groupList: [],
    totalUnread: { message: 0, notice: 0 },
    chattingUserInfo: null,
    chattingGroupInfo: null,
    noticeList: [],
    loading: false,
  }),
  getters: {
    activeSessionMessages: (state) => {
      const sessionId = state.chattingUserInfo?.sessionId
      if (!sessionId) return []
      const session = state.personMessage.find(pm => pm.sessionId === sessionId)
      if (!session) return []
      // 标记消息归属
      return session.list.map(msg => ({
        ...msg,
        isSelf: msg.senderId === state.loginUserInfo.uid
      }))
    },
  },
  actions: {
    login(userInfo) {
      this.hasLogin = !!localStorage.getItem('hasLogin')
      this.sessionKey = localStorage.getItem('sessionKey')
      this.loginUserInfo = userInfo
    },
    logout() {
      this.hasLogin = false
      this.sessionKey = null
      this.loginUserInfo = {}
    },
    setFriendList(list) {
      this.friendList = list
    },
    switchLoading(tf) {
      this.loading = typeof tf === 'boolean' ? tf : !this.loading
    },
    initSessionList() {
      this.totalUnread.message = 0
      this.sessionList = []
      for (let i = 0; i < this.friendList.length; i++) {
        let session = {
          type: 'person',
          avatar: this.friendList[i].avatar,
          sessionId: this.friendList[i].session_id,
          name: this.friendList[i].notation,
          lastMessage: this.friendList[i].last_message,
          isHidden: this.friendList[i].is_hidden,
          unread: this.friendList[i].unread,
          updateTime: this.friendList[i].update_time,
          chattingUserId: this.friendList[i].friend_id,
        }
        this.totalUnread.message += session.unread
        this.sessionList.push(session)
      }
      this.sortSessionList()
    },
    countUnreadMessage() {
      this.totalUnread.message = 0
      for (let i = 0; i < this.sessionList.length; i++) {
        this.totalUnread.message += this.sessionList[i].unread
      }
    },
    sortSessionList() {
      this.sessionList.sort((a, b) => b.updateTime - a.updateTime)
    },
    async getNoticeList() {
      const res = await request.get('notice/list')
      if (res.code === 0) {
        this.totalUnread.notice = res.data.count
        this.noticeList = res.data.noticeList
      }
    },
    initFriendSessionId() {
      for (let i = 0; i < this.friendList.length; i++) {
        let session = {
          sessionId: this.friendList[i].session_id,
          pageNum: 1,
          pageSize: 20,
          hasNextPage: false,
          lastMessageId: 0,
          list: [],
        }
        this.personMessage.push(session)
      }
    },
    async getFriendList() {
      const res = await request.get('friend/list')
      if (res.code === 0) {
        this.friendList = res.data
        this.initSessionList()
        this.initFriendListShow()
        this.initFriendSessionId()
      }
    },
    initFriendListShow() {
      this.friendListShow = Array.from({ length: 29 }, () => [])
      for (let i = 0; i < this.friendList.length; i++) {
        let t = {
          id: this.friendList[i].friend_id,
          name: this.friendList[i].notation,
          url: this.friendList[i].avatar,
        }
        let num = stringUtil.getFirstLetter(this.friendList[i].notation).charCodeAt(0)
        if (num >= 65 && num <= 90) {
          this.friendListShow[num - 63].push(t)
        } else {
          this.friendListShow[1].push(t)
        }
      }
    },
    async clearUnread(param) {
      await request.post('chat/clearUnread', param)
    },
    addPersonMessage(message) {
      console.log('[chatStore] addPersonMessage:', message)
      let found = false
      for (let i = 0; i < this.personMessage.length; i++) {
        if (this.personMessage[i].sessionId === message.sessionId) {
          this.personMessage[i].list.push(message)
          found = true
          break
        }
      }
      if (!found) {
        this.personMessage.push({ sessionId: message.sessionId, list: [message] })
      }
    },
    updateSessionList(message) {
      console.log('[chatStore] updateSessionList:', message)
      for (let i = 0; i < this.sessionList.length; i++) {
        if (this.sessionList[i].sessionId === message.sessionId) {
          this.sessionList[i].updateTime = message.updateTime
          switch (message.messageType) {
            case 'image':
              this.sessionList[i].lastMessage = '【图片】'
              break
            case 'file':
              this.sessionList[i].lastMessage = '【文件】'
              break
            case 'video':
              this.sessionList[i].lastMessage = '【视频】'
              break
            default:
              this.sessionList[i].lastMessage = message.content
          }
          if (
            !this.chattingUserInfo ||
            this.chattingUserInfo.sessionId !== this.sessionList[i].sessionId
          ) {
            if (message.senderId !== this.loginUserInfo.uid) this.sessionList[i].unread++
          } else {
            this.clearUnread({
              myId: this.loginUserInfo.uid,
              friendId: this.chattingUserInfo.chattingUserId,
            })
          }
          const session = this.sessionList.splice(i, 1)
          this.sessionList = session.concat(this.sessionList)
          break
        }
      }
    },
    setOnlineArray(arr) {
      console.log('[chatStore] setOnlineArray:', arr)
      this.onlineArray = Array.isArray(arr) ? [...arr] : []
    },
    setLastUpdateSession(sessionId) {
      this.lastUpdateSession = {
        id: sessionId,
        count: (this.lastUpdateSession.count || 0) + 1,
      }
    },
    withdrawMessage(sessionId, messageId) {
      for (let i = 0; i < this.personMessage.length; i++) {
        if (this.personMessage[i].sessionId === sessionId) {
          for (let j = this.personMessage[i].list.length - 1; j >= 0; j--) {
            if (this.personMessage[i].list[j].id === messageId) {
              this.personMessage[i].list[j].isWithdrawn = 1
              break
            }
          }
          break
        }
      }
    },
    setLoginUserInfo(userInfo) {
      this.loginUserInfo = userInfo
    },
    setChattingUserInfo(info) {
      this.chattingUserInfo = info
    },
    setActiveSession(sessionId) {
      console.log('[chatStore] setActiveSession:', sessionId)
      const session = this.sessionList.find(s => s.sessionId === sessionId)
      if (session) {
        this.chattingUserInfo = session
        // 清除未读
        this.clearUnread({
          myId: this.loginUserInfo.uid,
          friendId: session.chattingUserId,
        })
        session.unread = 0
        this.countUnreadMessage()
      }
    },
    sendMessage(content) {
      console.log('[chatStore] sendMessage:', content)
      if (!this.chattingUserInfo) return
      const msg = {
        type: 'person-message',
        data: {
          sessionId: this.chattingUserInfo.sessionId,
          senderId: this.loginUserInfo.uid,
          receiverId: this.chattingUserInfo.chattingUserId,
          sendTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
          content,
          messageType: 'text',
        }
      }
      console.log('[chatStore] sendMessage:', msg)  
      // 检查 socket 状态
      const globalStore = useGlobalStore()
      if (!globalStore.isSocketOpen) {
        if (typeof window !== 'undefined' && window.ElMessage) {
          window.ElMessage.error('消息发送失败，连接已断开')
        }
        websocket.initConnect && websocket.initConnect()
        return
      }
      websocket.sendMessage(msg)
    },
  },
}) 